package com.hankol.winecellar

import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.manager.DialogManager
import com.baselibrary.manager.FlowLayoutManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.CommonUtil
import com.baselibrary.utils.HKUtils
import com.baselibrary.utils.SpUtils
import com.baselibrary.view.SpaceItemDecoration
import com.hankol.newretail.fragment.MyOrderFragment
import com.hankol.newretail.viewmodel.OrderAboutViewModel
import com.hankol.winecellar.adapter.SearchHistory4GoodsOrderAdapter
import com.hankol.winecellar.databinding.ActivitySearchOrderBinding
import com.hankol.winecellar.fragment.GoodsOrderFragment
import com.hankol.winecellar.help.NativeHelp

/**新零售-搜索订单
 * @author: merbng
 * @time: 2022/8/5 9:48
 * @description:
 */
@Route(path = ActivityRouter.WINE_CELLAR.SEARCH_ORDER)
class SearchOrderActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: OrderAboutViewModel
    private lateinit var binding: ActivitySearchOrderBinding
    private val nativeHelp: NativeHelp = ActivityRouter.getARouterInterface(ActivityRouter.ACTIVITY.NATIVE_HELP)
    private var historyAdapter: SearchHistory4GoodsOrderAdapter? = null
    val userIdStr by lazy { SpUtils.getInstance().loadUserBean.data.id }

    val saleOrderFragment by lazy { GoodsOrderFragment.newInstance(-1) }
    val myOrderFragment by lazy { MyOrderFragment.newInstance(-1) }
    var isManager = false
    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_search_order
    }

    override fun init() {
        setStatusBarHeight(R.color.white)
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(OrderAboutViewModel::class.java)
        initView()
        initListener()
        initObserver()
    }

    private fun initListener() {
        binding.ivSearchClear.setOnClickListener(this)
        binding.imgClose.setOnClickListener(this)
        binding.ivClearHistory.setOnClickListener(this)
        binding.etSearch.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val content: String = binding.etSearch.text.toString().trim().replace("\\s".toRegex(), "")
                if (!CommonUtil.isBlank(content)) {
                    if (content.length >= 1) {
                        // 隐藏键盘
                        if (HKUtils.isFastClick()) {
                            content?.let {
                                nativeHelp.saveHistory4Order(isManager, userIdStr, it)
                                hideSoftKeyboard()
                                searchResult(content)
                            }
                        }
                    } else {
                        showToast("请输入搜索关键词")
                    }

                } else {
                    showToast("请输入搜索关键词")
                }
                return@OnEditorActionListener true
            }
            false
        })
    }

    private fun initView() {
        if (intent.extras.checkNotNull()) {
            isManager = intent.extras!!.getBoolean(Constants.KEY_SEARCH_ORDER_IS_MANAGER)
        }
        binding.etSearch.requestFocus()
        //历史记录
        historyAdapter = SearchHistory4GoodsOrderAdapter(this)
        historyAdapter?.setOnItemClickListener { _, _, position ->
            val item = historyAdapter?.getItem(position)
            binding.etSearch.setText(item)
            binding.etSearch.setSelection(binding.etSearch.text.length)
            if (HKUtils.isFastClick()) {
                item?.let {
                    nativeHelp.saveHistory4Order(isManager, userIdStr, it)
                    //搜索结果
                    hideSoftKeyboard()
                    searchResult(it)
                }
            }
        }
        binding.historySearchRecyclerView.adapter = historyAdapter
        binding.historySearchRecyclerView.addItemDecoration(SpaceItemDecoration(CommonUtil.dip2px(this, 10f)))
        binding.historySearchRecyclerView.layoutManager = FlowLayoutManager()
        binding.historySearchRecyclerView.isNestedScrollingEnabled = false
        //搜索输入内容
        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                binding.ivSearchClear.visibility = if (CommonUtil.isBlank(s.toString())) View.GONE else View.VISIBLE

            }

            override fun afterTextChanged(s: Editable) {
            }
        })


        val contentFragment = if (isManager) saleOrderFragment else myOrderFragment
        val manager = supportFragmentManager
        val transaction = manager.beginTransaction()
        transaction.replace(R.id.container, contentFragment)
        transaction.commit()
    }

    private fun searchResult(content: String) {
//        EventBusUtils.sendNotify1Value(MessageBus.msgId_search_order, content)
        binding.llHistorySearch.visibility = View.GONE
        binding.container.visibility = View.VISIBLE
        saleOrderFragment.setKeyWord(content)
        myOrderFragment.setKeyWord(content)
        if (isManager) saleOrderFragment.loadData(true) else myOrderFragment.loadData(true)
    }

    private fun initObserver() {

    }

    /**
     * 清除历史搜索记录
     */
    fun cleanHistory() {
        DialogManager.showConfirmDialog(this, "确定删除历史搜索", object : DialogManager.Listener {
            override fun onItemLeft() {

            }

            override fun onItemRight() {
                nativeHelp.cleanHistory4Order(isManager, userIdStr)
                fillHistory()
            }
        })
    }

    fun fillHistory() {
        val historyList = nativeHelp.getHistory4Order(isManager, userIdStr)
        if (null != historyList && historyList.size > 0) {
            historyAdapter?.data = addToTreeList(historyList)
            binding.deleteSearchView.visibility = View.VISIBLE
            binding.ivClearHistory.visibility = View.VISIBLE
        } else {
            if (null != historyAdapter && null != historyAdapter?.data) {
                historyAdapter?.clearData()
            }
            binding.deleteSearchView.visibility = View.GONE
            binding.ivClearHistory.visibility = View.GONE
        }
    }

    /**
     *排序
     */
    private fun addToTreeList(list: List<String>): List<String> {
        return if (list.size > 20) {
            list.subList(0, 20)
        } else {
            list
        }
    }

    override fun onResume() {
        fillHistory()
        super.onResume()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.img_close -> {
                finish()
            }
            R.id.iv_search_clear -> {
                binding.etSearch.setText("")
                binding.llHistorySearch.visibility = View.VISIBLE
                binding.container.visibility = View.GONE
                fillHistory()
            }
            R.id.iv_clear_history -> {
                cleanHistory()
            }
        }
    }
}